package com.leyou.item.service.Impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.item.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;


/**
 * Author: Saka
 * Date: 2019/1/17
 * Time: 21:01
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private FastFileStorageClient fsClient;
    @Override
    public String upload(MultipartFile file) {

        //图片校验
        //校验文件类型
        try {
            //校验图片类型
            Set<String> allowExt = new HashSet<>();
            allowExt.add("image/jpeg");
            allowExt.add("image/png");
            String contentType = file.getContentType();
            if (!allowExt.contains(contentType)) {
                return null;
            }

            //校验图片的类型

            BufferedImage read = ImageIO.read(file.getInputStream());
            if (null == read) {
                return null;
            }
            //获取文件的后缀
            String ext = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            //上传文件并获取文件的id信息
            StorePath storePath = fsClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            //给文件的id信息拼接前缀地址
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
